const socketServer = require("websocket").server;
const { createServer } = require("http");
const server = createServer();
server.listen(3000, '172.16.34.171',() => {
  console.log("服务器开启");
});
const wsServer = new socketServer({
  httpServer: server,
});
let conArr = [];

let userlist = [];
let msglist = [];
let isNewUser = false;
usercontroller = function (username) {
  if (!userlist.length) {
    userlist.push(username);
    return true;
  }
  const index = userlist.findIndex((user) => user == username);
  if (index !== -1) {
    return false;
  }
  userlist.push(username);
  return true;
};
msgcontroller = function (sendMsgObj) {
  let text = sendMsgObj.text
  if (text !== "\n" && text) {
    msglist.push(sendMsgObj);
  }
};
wsServer.on("request", (request) => {
  const connection = request.accept();
  conArr.push(connection);
  connection.on("message", (msg) => {
    const sendMsgObj = JSON.parse(msg.utf8Data);
    console.log(sendMsgObj);
    isNewUser = usercontroller(sendMsgObj.username);
    if (isNewUser){
      msglist.push({
        addUser: true,
        name: sendMsgObj.username,
      });
    }
    msgcontroller(sendMsgObj);
    const msgObj = {
      userlist,
      msglist,
    };
    for (let i = 0; i < conArr.length; i++) {
      conArr[i].send(JSON.stringify(msgObj));
    }
  });
});
